'use strict';
const Controller = require('egg').Controller;
const md5 = require('md5');
const mongoose = require('mongoose');
class AdminController extends Controller {
    async add(){
        const {ctx,service} = this;
        try {
            let {username,password} = ctx.request.body;
            let res = await service.admin.isadmin(username);
            if(res.data==1){
                password = md5(md5(password).substr(4,6) + md5(password));
                let result = await service.normal.addinfo('Admin',{username,password,phone:username});
                ctx.body = result;
            }else{
                ctx.body = res;
            }
        } catch (error) {
            ctx.body = {data:0,error}
        }
    }

    async upAdminAll(){
        const {ctx,service} = this;
        let {id,json} = ctx.request.body;
        let result = await ctx.model.Admin.findOne({ _id: mongoose.mongo.ObjectId(id) })
        if(result){
            let result = await service.normal.updateinfobyid('Admin',id,json);
            ctx.body = result;
            return null;
        }else{
            ctx.body = {data:0, content: "商家不存在！"}
        }
    }
    
    async deleteAdmin(){
        const {ctx,service} = this;
        let {id} = ctx.request.body;
        let result = await ctx.model.Admin.findOne({ _id: mongoose.mongo.ObjectId(id) })
        if(result){
            await service.normal.remTable('Admin',id);
            await service.normal.remTabless('Consume',{shopid: id});
            await service.normal.remTabless('Order',{shopid: id});
            await service.normal.remTabless('AdminTab',{userId: id});
            await service.normal.remTabless('Recharge',{shopid: id});
            ctx.body = {data:1, content: "删除商家成功！"}
            return null;
        }else{
            ctx.body = {data:0, content: "商家不存在！"}
        }
    }

    async upassword(){
        try {
            const {ctx,service} = this;
            let {id,newpass} = ctx.request.body; 
            let npass = md5(md5(newpass).substr(4,6) + md5(newpass));
            let jsons = {
                $set:{password: npass}
            }
            let result = await service.normal.updateinfobyid('Admin',id,jsons);
            ctx.body = result;
        } catch (error) {
            ctx.body = {data:0,error}
        }
    }
    

    async updateadmin(){
        const {ctx,service} = this;
        let {id,type,json,count} = ctx.request.body;
        if(type==1){
            let result = await ctx.model.Admin.findOne({ _id: mongoose.mongo.ObjectId(id) })
            if(result.nickName==count){
                ctx.body = {data:0,content:'你未对名字进行修改！'}
                return null;
            }else{
                let resultss = await ctx.model.Admin.findOne({ nickName: count })
                if(resultss){
                    ctx.body = {data:0,content: count+'已有，不可用'}
                    return null;
                }else{
                    let result = await service.normal.updateinfobyid('Admin',id,json);
                    ctx.body = result;
                    return null;
                }
            }
        }else if(type==2){
            let result = await ctx.model.Admin.findOne({ _id: mongoose.mongo.ObjectId(id) })
            let password = md5(md5(json).substr(4,6) + md5(json));
            if(password!=result.password){
                ctx.body = {data:0,content: '原密码错误？'}
            }else{
                let npass = md5(md5(count).substr(4,6) + md5(count));
                let jsons = {
                    $set:{password: npass}
                }
                let result = await service.normal.updateinfobyid('Admin',id,jsons);
                ctx.body = result;
            }
        }else if(type==3){
            let result = await service.normal.updateinfobyid('Admin',id,json);
            ctx.body = result;
        }
    }


    async pageAdmin(){
        const {ctx,service} = this;
        let {json,page,size,paixu} = ctx.request.body;
        let px = paixu==null?{ create_at: -1 }:paixu;
        let result = await service.normal.getinfos('Admin',json,page,size,px);
        ctx.body = result;
    }

    async pageAuthority(){
        const {ctx,service} = this;
        let {json,page,size,paixu} = ctx.request.body;
        let px = paixu==null?{ create_at: -1 }:paixu;
        let result = await service.normal.getinfos('Admin',json,page,size,px);
        for(let i=0;i<result.result.result.length;i++){
            let tabs = await ctx.model.AdminTab.findOne({ userId: result.result.result[i]._id })
            let tab = tabs==null?[]:tabs.array
            result.result.result[i].tab = tab;
        }
        ctx.body = result;
    }


    async isAdminName(){
        const {ctx,service} = this;
        if(ctx.session.admin && ctx.session.islogin){
            let {id,nickName} = ctx.request.query;
            let result = await ctx.model.Admin.findOne({ _id: mongoose.mongo.ObjectId(id) })
            if(result.nickName==nickName){
                ctx.body = {data:1,content:'你未对名字进行修改！'}
                return null;
            }else{
                let resultss = await ctx.model.Admin.findOne({ nickName: nickName })
                if(resultss){
                    ctx.body = {data:0,content: nickName+'已有，不可用'}
                    return null;
                }else{
                    ctx.body = {data:1,content: nickName+'暂无，可用'}
                    return null;
                }
            }
        }else{
            ctx.body = {data:0,content:'暂未登录'}
        }
    }

    async requeAdminData(){
        const {ctx,service} = this;
        let time = new Date()
        var year = time.getFullYear(); //获取年  
        var month = time.getMonth() + 1;//获取月份，获取的月份比真实的月份少一个月，所以这里得+1   
        var day = time.getDate();  //获取日
        let times = year + "-" + month + "-" + day;
        let adminSum = await ctx.model.Admin.count({toplvid: ctx.session.admin._id})
        let adminSumday = await ctx.model.Admin.count({ create_at: { $gt: new Date([year, month, day]) }, toplvid: ctx.session.admin._id})
        let userSum = await ctx.model.User.count({shoptoplvid: ctx.session.admin._id})
        let userSumday = await ctx.model.User.count({ create_at: { $gt: new Date([year, month, day]) }, shoptoplvid: ctx.session.admin._id})
        let replySum = await ctx.model.Reply.count({atype: 2,shoptoplvid: ctx.session.admin._id,isShow: false})
        let consumeSum = await ctx.model.Order.count({shoptoplvid: ctx.session.admin._id, buy:true})
        let moneyre = await ctx.model.Recharge.aggregate([{ $match: { shoptoplvid: ctx.session.admin._id } },{ $group: { _id: null, count: { $sum: "$money" } } }]);
        let money = 0;
        if (moneyre.length > 0) {
            money = moneyre[0].count.toFixed(2)
        }
        ctx.body = {data:1,content:{adminSum,adminSumday,userSum,userSumday,replySum,consumeSum,money}};
    }

    async requewxAdminData(){
        const {ctx,service} = this;
        let time = new Date()
        var year = time.getFullYear(); //获取年  
        var month = time.getMonth() + 1;//获取月份，获取的月份比真实的月份少一个月，所以这里得+1   
        var day = time.getDate();  //获取日
        let times = year + "-" + month + "-" + day;
        let orderSum = await ctx.model.Order.count({shopid: ctx.session.admin._id})
        let orderSumday = await ctx.model.Order.count({ create_at: { $gt: new Date([year, month, day]) }, shopid: ctx.session.admin._id})
        let moneyre = await ctx.model.Recharge.aggregate([{ $match: { shopid:  ctx.session.admin._id} },{ $group: { _id: null, count: { $sum: "$money" } } }]);
        let moneydayre = await ctx.model.Recharge.aggregate([{ $match: { create_at: { $gt: new Date([year, month, day]) }, shopid: ctx.session.admin._id } }, { $group: { _id: null, count: { $sum: "$money" } } }]);
        let money = 0;
        if (moneyre.length > 0) {
            money = moneyre[0].count.toFixed(2)
        }
        let moneyday = 0;
        if (moneydayre.length > 0) {
            moneyday = moneydayre[0].count.toFixed(2)
        }
        ctx.body = {data:1,content:{orderSum,orderSumday,money,moneyday}};
    }


    async requeAdminid(){
        const {ctx,service} = this;
        if(ctx.session.admin && ctx.session.islogin){
            let data = ctx.request.query;
            let result = await service.normal.getinfobyid('Admin',data.id);
            ctx.body = result;
        }else{
            ctx.body = {data:0,content:'暂未登录'}
        }
    }


    async addadmin(){
        const {ctx,service} = this;
        try {
            if(ctx.session.role!="admin"){
                ctx.body = {data:0,content:'登录已过期，无法添加'};
                return null;
            }
            let {username,password} = ctx.request.body;
            let form = ctx.request.body;
            let res = await service.admin.isadmin(username);
            if(res.data==1){
                password = md5(md5(password).substr(4,6) + md5(password));
                form.password = password;
                form.phone = username;
                form.toplvid =  ctx.session.admin._id;
                let result = await service.normal.addinfo('Admin',form);
                ctx.body = result;
            }else{
                ctx.body = res;
            }
        } catch (error) {
            ctx.body = {data:0,error}
        }
    }
    async islogin(){
        const {ctx,service} = this;
        if(ctx.session.admin && ctx.session.islogin){
            let result = await ctx.model.Admin.findOne({ _id: mongoose.mongo.ObjectId(ctx.session.admin._id) });
            if(result){
                result.password=null;
                ctx.body = {data:1, result};
            }else{
                ctx.body = {data:0,content:'暂未登录'}
            }
        }else{
            ctx.body = {data:0,content:'暂未登录'}
        }
    }
    async login(){
        const {ctx,service} = this;
        let {username,password} = ctx.request.body;
        let result = await service.admin.login(username,password);
        ctx.body = result;
    }
    async outlogin(){
        const {ctx,service} = this;
       try {
        ctx.session.admin = null;
        ctx.body = {data:1,content:'已退出'};
       } catch (error) {
        ctx.body = {data:0,error};
       }
    }
    async gets(){
        const {ctx,service} = this;
        let { servicesType,page,size,toplvid,level} = ctx.request.body;
        let result = await service.normal.getinfos('Admin',{level,servicesType,toplvid},page,size);
        ctx.body = result;
    }
    async getbyid(){
        const {ctx,service} = this;
        const {id} = ctx.request.body;
        let result = await service.normal.getinfobyid('Admin',id);
        ctx.body = result;
    }
}

module.exports = AdminController;
